package com.example.okhttps;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;

import com.ejlchina.okhttps.HttpTask;

public class LcObserver implements LifecycleObserver {

    private HttpTask<?> task;
    private Lifecycle lifecycle;
    private Object bound;

    LcObserver(HttpTask<?> task, Object bound) {
        this.task = task;
        if (bound instanceof LifecycleOwner) {
            lifecycle = ((LifecycleOwner) bound).getLifecycle();
            lifecycle.addObserver(this);
        }
        this.bound = bound;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onStop() {
        task.cancel();  // 在 ON_STOP 事件中，取消对应的 HTTP 任务
    }

    void unbind() {
        if (lifecycle != null) {
            lifecycle.removeObserver(this);
        }
    }

    public Object getBound() {
        return bound;
    }

}
